package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.sun.xml.bind.v2.model.core.ID;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.apache.bcel.generic.RET;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.rmi.runtime.NewThreadAction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MovementsService {
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private CommentsApi commentsApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private MqMessageService mqMessageService;


    //发布动态
    public void save(MultipartFile[] imageContent, String textContent, String location, String longitude, String latitude) throws IOException {
        //获取id
        Long userId = UserHolder.getUserId();
        //构建对象
        Movement movement = new Movement();
        movement.setUserId(userId);
        movement.setTextContent(textContent);
        movement.setLongitude(longitude);
        movement.setLatitude(latitude);
        movement.setLocationName(location);
        movement.setCreated(System.currentTimeMillis());
        List<String> medias = new ArrayList<>();
        //上传图片
        for (MultipartFile image : imageContent) {
            //路径   上传到阿里云
            String url = ossTemplate.upload(image.getInputStream(), image.getOriginalFilename());
            medias.add(url);
        }
        movement.setMedias(medias);
        //保存 返回动态id
       String id =  movementApi.save(movement);
        //发送消息  审核
        mqMessageService.sendAudiMessage(id);
    }
    //查询个人
    public PageResult all(Long userId, Integer page, Integer pagesize) {
        //查询个人动态
        List<Movement>  list =movementApi.findByUserId(userId,page,pagesize);
        //判断是否为空
        if (CollUtil.isEmpty(list)){
            return  new PageResult();
        }
        //查询个人用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        List<MovementsVo> vos = new ArrayList<>();
        //个人和动态信息合并返回
        for (Movement movement : list) {
            MovementsVo vo = MovementsVo.init(userInfo, movement);
           //todo  跟老师不一样  这边暂时不写  我写在了 公共方法上
            //从redis中查询喜欢状态
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }
    //查询好友动态
    public PageResult findByFriendsId(Integer page, Integer pagesize) {
        //获取userId
        Long friendId = UserHolder.getUserId();
        //查询动态
       List<Movement> list = movementApi.findByFriendsId(friendId,page,pagesize);
        return initPage(list,page,pagesize);
    }

    //公共的方法
    private PageResult initPage (List<Movement> list,Integer page, Integer pagesize) {
        //3、判断动态列表是否为空
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //一次性查询
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);//list，属性名，类型

        Map<Long,UserInfo> map = userInfoApi.findByIds(userIds);
        //信息合并
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : list) {
            UserInfo info = map.get(movement.getUserId());
            MovementsVo vo = MovementsVo.init(info, movement);//用户信息，动态详情
            //从redis 中查询是否点赞
            String redisLikeKey = Constants.MOVEMENTS_INTERACT_KEY + vo.getId();
            String hashLikeKey = Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();

            //从redis中查询点赞状态
            Boolean like = stringRedisTemplate.opsForHash().hasKey(redisLikeKey, hashLikeKey);
            //从redis 中查询是否喜欢
            String redisLoveKey = Constants.MOVEMENTS_INTERACT_KEY +vo.getId();
            String hashLoveKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
            //从redis中查询点赞状态
            Boolean love = stringRedisTemplate.opsForHash().hasKey(redisLoveKey, hashLoveKey);

            if (like){
                vo.setHasLiked(1);
            }
            if (love){
                vo.setHasLiked(1);
            }
            vos.add(vo);
        }
        //5、返回
        return new PageResult(page,pagesize,0l,vos);
    }
    //查询推荐动态
    public PageResult findByRecommend(Integer page, Integer pagesize) {
        //获取id
        Long userId = UserHolder.getUserId();
        //从redis获取数据
        String key = Constants.MOVEMENTS_RECOMMEND + userId;
        String value = stringRedisTemplate.opsForValue().get(key);
        List<Movement> list = new ArrayList<>();
        //判断数据是否存在
        if (StringUtils.isNotEmpty(value)){
            //拆分数据
            String[] ids = value.split(",");
            list =  movementApi.findByIds(ids,page,pagesize);

        }else {
            //不存在随机
            list =movementApi.randomMovement(pagesize);
        }
        return initPage(list,page,pagesize);
    }
        //根据id查询动态
    public MovementsVo findById(String id) {
        //查询动态
        Movement movement =   movementApi.findById(id);
        //查询发布人信息
        Long userId = movement.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        MovementsVo vo = MovementsVo.init(userInfo, movement);
        return vo;

    }
    //点赞
    public Integer like(String id) {
        Comment comment = new Comment();
        //设置动态id
        comment.setPublishId(new ObjectId(id));
        //设置类型 点赞-1
        comment.setCommentType(1);
        //设置点赞的id
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        System.out.println(id);
        //保存
        Integer count = commentsApi.saveComments(comment);
//        //存入redis

        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();

        stringRedisTemplate.opsForHash().put(redisKey,hashKey,"1");
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0203","log.movement",id);
        return count;
    }
    //取消点赞
    public Integer dislike(String movementId) {
        Integer commentType = 1;
        Long userId = UserHolder.getUserId();
        //删除
        Integer count =  commentsApi.deleteComments(movementId,userId,commentType);

        //删除redis
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();
        redisTemplate.opsForHash().delete(redisKey,hashKey);
        return count;
    }
    //喜欢
    public Integer love(String movementId) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(3);
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.saveComments(comment);
        //存入redis
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY +movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        stringRedisTemplate.opsForHash().put(redisKey,hashKey,"1");
        return count;
    }
    //取消喜欢
    public Integer unlove(String movementId) {
        Integer commentType = 3;
        Long userId = UserHolder.getUserId();
        //删除
        Integer count =  commentsApi.deleteComments(movementId,userId,commentType);

        //删除redis
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY +movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(redisKey,hashKey);
        return count;
    }
}
